package web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import web.misc.JsonHttpResponseWriter;
import web.servlet.dto.DtoFactory;
import data.dao.DataFacade;
import data.model.User;

public class AuthenticationFilter implements Filter {

    private DataFacade dataLayer;

    private JsonHttpResponseWriter jsonHandler;

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if ("joinGroup".equals(request.getParameter("action"))) {
            filterChain.doFilter(request, response);
        } else {
            final String email = request.getParameter("email");
            final String accessToken = request.getParameter("accessToken");

            final User user = dataLayer.findUserByEmail(email);
            if (user == null) {
                jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid user"), response);
            } else if (!user.getCurrentAccessToken().equals(accessToken)) {
                jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid access token"), response);
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {
        this.dataLayer = (DataFacade) config.getServletContext().getAttribute("dataLayer");
        this.jsonHandler = (JsonHttpResponseWriter) config.getServletContext().getAttribute("jsonHandler");
    }

}
